package cn.tedu.jxdm.controller;

import cn.tedu.jxdm.ex.ServiceException;
import cn.tedu.jxdm.web.JsonResult;
import cn.tedu.jxdm.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e) {
        return JsonResult.fail(e);
    }
    @ExceptionHandler
    public JsonResult handlerBindException(BindException e){
        // 使用以下方式时，如果有多个检查错误，
        // 将获取其中某1个检查注解中配置的message值，但无法确定到底是哪一个
//        StringJoiner stringJoiner = new StringJoiner("，", "请求参数格式错误，", "！");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for (FieldError fieldError : fieldErrors) {
//            stringJoiner.add(fieldError.getDefaultMessage());
//        }
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }
    @ExceptionHandler
    public JsonResult handlerConstraintViolationException(ConstraintViolationException e){
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String message=null;
        for (ConstraintViolation<?> constraintViolation:constraintViolations){
            message=constraintViolation.getMessage();
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }
    @ExceptionHandler
    public JsonResult handlerThrowable(Throwable e){
        String message="服务器忙,请稍后再试";
        log.warn("异常类型:{}",e.getClass().getName());
        log.warn("异常信息:{}",e.getMessage());
        log.warn("异常:",e);
        return JsonResult.fail(ServiceCode.ERR_UNKNOWN,message);
    }

}
